package com.ccp.dev.workflow.event;

import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.workflow.model.ProcessRun;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;

/**
 * ClassDescribe:
 * 触发新流程事件。
 *
 * @author :wangcheng
 * Date: 2019-12-25
 */
@Component
@Scope("prototype")
public class TriggerNewFlow implements Runnable{
    private static Logger logger = LoggerFactory.getLogger(TriggerNewFlow .class);
    private CountDownLatch latch;
    private Exception exception;
    @Resource
    ProcessRunService processRunService;

    ProcessCmd cmd;
    SysUser user;

    @Override
    public void run() {
        try {
            if (cmd == null || user == null) {
                throw new RuntimeException("触发新流程失败！ new flow Cmd or starUser cannot be null");
            }
            ContextUtil.setCurrentUser(user);
            ProcessRun run = processRunService.startProcess(cmd);
            logger.debug("新流程启动成功！ runId:" + run.getRunId());
            latch.countDown();
        } catch (Exception e) {
            this.exception = e;
            latch.countDown();
            logger.error("触发新流程流程失败！"+e.getMessage());
            e.printStackTrace();
        }
    }


    public Exception getException() {
        return exception;
    }

    public void setException(Exception exception) {
        this.exception = exception;
    }

    public CountDownLatch getLatch() {
        return latch;
    }

    public void setLatch(CountDownLatch latch) {
        this.latch = latch;
    }

    public void setCmd(ProcessCmd cmd) {
        this.cmd = cmd;
    }

    public void setUser(SysUser user) {
        this.user = user;
    }

}
